﻿using System;
using System.Data;
using System.Collections.Generic;
using Finance.Data.Entities;

namespace Finance.Data
{
	internal class Notes : DataBaseObjectCollection<Note>, INotes
	{
		private readonly FinanceDataBase _dataBase;

		private const string CreateNoteQuery = "insert into note (createdon, text) values(@p0, @p1)";
               
		private const string RetrieveNoteQuery =
			"select [text], noteid, createdon from note where createdon >= @p0 and createdon <@p1";

		private const string UpdateNoteQuery = "update note set text = @p1 where noteid = @p0";

		public Notes(FinanceDataBase dataBase) : base(dataBase, "note")
		{
			_dataBase = dataBase;
		}

		public List<Note> RetrieveNotes(DateTime date)
		{
			var notes = new List<Note>();

			using (IDataReader dataReader = _dataBase.Sql.ExecuteReader(RetrieveNoteQuery, date.Date, date.Date.AddDays(1)))
			{
				while (dataReader.Read())
				{
					var note = ParseItem(dataReader);
					notes.Add(note);
				}
			}

			return notes;
		}

		protected override Note ParseItem(IDataRecord dataReader)
		{
			return new Note(this)
			{
				Id = (Guid)dataReader["noteid"],
				Text = (string)dataReader["text"],
				DateTime = (DateTime)dataReader["createdon"]
			};
		}

		protected override void Update(Note item)
		{
			_dataBase.Sql.ExecuteNonQuery(UpdateNoteQuery, item.Id, item.Text);
		}

		protected override void Insert(Note item)
		{
			_dataBase.Sql.ExecuteNonQuery(CreateNoteQuery, item.DateTime, item.Text);
		}

		public override Note NewItem()
		{
			return new Note(this);
		}
	}
}
